package www.study.com;

//在排序数组中查找元素的第一个和最后一个位置 https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
public class code34 {
    public static void main(String[] args) {

    }

    class Solution {
        public int[] searchRange(int[] nums, int target) {
            int index1 = lefLeIndex(nums,target);
            int index2 = index1 == -1 ? -1 : rigLeIndex(nums,target);
            int[] res = {index1,index2};
            return res;
        }
        public int rigLeIndex(int[] nums,int target){
            int l = 0;
            int r = nums.length - 1;
            int mid = 0;
            int res = -1;
            while(l <= r){
                mid = l + ((r - l) >> 1);
                if(nums[mid] == target){
                    res = mid;
                    l = mid + 1;
                }else if(nums[mid] > target){
                    r = mid - 1;
                }else{
                    l = mid + 1;
                }
            }
            return res;
        }
        public int lefLeIndex(int[] nums,int target){
            int l = 0;
            int r = nums.length - 1;
            int mid = 0;
            int res = -1;
            while(l <= r){
                mid = l + ((r - l) >> 1);
                if(nums[mid] == target){
                    res = mid;
                    r = mid - 1;
                }else if(nums[mid] > target){
                    r = mid - 1;
                }else{
                    l = mid + 1;
                }
            }
            return res;
        }
    }
}
